package com.lovemanai.listener;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;

public class MyReadListener implements ReadListener{
	
	private ServletInputStream input;
	private AsyncContext actx;
	
	public MyReadListener(ServletInputStream input, AsyncContext asyncContext) {
		this.input = input;
		this.actx = asyncContext;
	}

	@Override
	public void onAllDataRead() throws IOException {
		System.out.println("所有数据读取完成。。。");
		
	}

	@Override
	public void onDataAvailable() throws IOException {
		System.out.println("数据可用");
		try {
			//暂停3秒，模拟读取数据为耗时操作
			Thread.sleep(3 * 1000);
			StringBuilder sb = new StringBuilder();
			
			int len = -1;
			byte[] bytes = new byte[1024];
			System.out.println(input.isReady());
 			while(input.isReady() && (len = input.read(bytes)) > 0) {
				String data = new String(bytes, 0, len);
				sb.append(data);
			}
			System.out.println(sb);
			actx.getRequest().setAttribute("info", sb.toString());
			
			actx.dispatch("/async2.jsp");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public void onError(Throwable t) {
		t.printStackTrace();
	}

}
